#include "extractthread.h"
#include <QProcess>
#include <QStandardPaths>
#include <QDir>
#include <QDebug>

extractThread::extractThread(QObject *parent) : QThread(parent)
{
    tempFileName = QStandardPaths::writableLocation(QStandardPaths::TempLocation)+"/squashfs-root";
}

quint64 extractThread::getMaxSize(QString path)
{
    QDir dir(path);
    quint64 size = 0;
    //dir.entryInfoList(QDir::Files)返回文件信息
    foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files))
    {
    //计算文件大小
        size += fileInfo.size();
    }
    //dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)返回所有子目录，并进行过滤
    foreach(QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
    {
    //若存在子目录，则递归调用dirFileSize()函数
        size += getMaxSize(path + QDir::separator() + subDir);
    }
    return size;
}

void extractThread::recvFileName(QString name)
{
    m_fileName = name;
}

void extractThread::run()
{
    qDebug()<<"子线程进行";
    QProcess* process = new QProcess;
    process->setWorkingDirectory(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
    if(QDir(tempFileName).exists()){
        QDir(tempFileName).removeRecursively();
    }

    QStringList cmdStrList;
    cmdStrList << "--appimage-extract";

    QFile(m_fileName).setPermissions(QFileDevice::ExeOwner|QFileDevice::WriteOwner|QFileDevice::ReadOwner);

    process->start(m_fileName,cmdStrList);
    if(!process->waitForFinished())
    {
        process->close();
        bool status = false;
    }
    process->close();
    bool status = true;
    emit sendStatus(status);
    emit sendData(getMaxSize(tempFileName));
    qDebug()<<"子线程结束";

}


